'''
Created on Jun 27, 2012

@author: cgiacofe
'''

import time
from datetime import datetime
from xml.etree import ElementTree as ET
from xml.dom import minidom

def current_hour():
    current_time = str(datetime.time(datetime.now())).split(':')
    return float(current_time[0])

def get_time():
    '''Returns a nicely formatted current time
    '''
    return time.asctime( time.localtime(time.time()))

def time_convert(seconds):
    '''Converts time in seconds into d:h:m:s
    '''
    m, s = divmod(seconds, 60)
    h, m = divmod(m, 60)
    d, h = divmod(h, 24)
    return "%d:%02d:%02d:%02d" % (d, h, m, s)

def write_log(output, aw='a', log_file='vpnlog.txt'):
    '''Appends the given output to a log file
    
    @param output: Text to be written to the file
    @type output: string
    
    @param aw: file open parameter (a=append, w=overwrite)
    @type aw: strign
    
    @param log_file: File to write to
    @type log_file: string
    '''
    log_out = open(log_file, aw)
    log_out.write(output + '\n')
    log_out.close()

def write_config(filename, text):
    '''Writes given text to a file. Will over-write 
    existing text in the file.
    
    @param filename: Name of file to write to
    @type filename: string
    
    @param text: Text to be writtent to the file
    @type text: string
    '''
    f = open(filename, 'w')
    f.write(text)

def write_xml(entry, filename, mode='append'):
    
    if mode == 'append':
        try:
            root = ET.parse(filename).getroot()
        except:
            print('No file found, creating new.')
            root = ET.Element('Log')
    elif mode == 'write':
        root = ET.Element('Log') 

    for line in entry:
        new_xml = _add_line(root, entry[line])
        
    new_xml = _prettify(new_xml)

    xml_file = open(filename, 'w')
    xml_file.write(new_xml)
    #ET.ElementTree(new_xml).write(filename)
    
def _prettify(elem):
    """Return a pretty-printed XML string for the Element.
    """
    rough_string = ET.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="\t")

def _add_line(root, entry):
    
    line_item = ET.SubElement(root, 'log_line')
    for key in entry.keys():
        ET.SubElement(line_item, key).text = str(entry[key])

    return root

if __name__ == '__main__':
    pass